package controller;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import java.io.PrintWriter;
import java.io.IOException;

import model.Users;
import model.q;
import dao.QDao;

public class QController extends HttpServlet {

    public QController(){
        super();
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        Users user = (Users)request.getSession().getAttribute("users");
        if(user == null){
            request.setAttribute("error","please login");
            request.getRequestDispatcher("/qa1.jsp").forward(request,response);
        }
        else {
            String question = (String) request.getParameter("question");
            String questionerID = user.getIdusers();
            String questionContext = (String) request.getParameter("context");
            q q = new q(question,questionerID,questionContext);
            QDao qdao = new QDao();
            if(question==null){
                request.setAttribute("error","please input your question and context");
                request.getRequestDispatcher("/qa1.jsp").forward(request,response);
            }
            else{
                try{
                    int i = qdao.save(q);
                    if(i==1){
                        response.sendRedirect(request.getContextPath()+"/qa1.jsp");
                    }
                    else{
                        request.setAttribute("error","failed");
                        request.getRequestDispatcher("/login.jsp").forward(request,response);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


}
